package com.javacoo.event.client.support.asm;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;

import com.javacoo.event.client.annotation.MySubscribe;
import com.javacoo.event.client.starter.EventHolder;
import com.javacoo.event.client.support.ApplicationContextProvider;
import com.javacoo.event.client.support.BaseEventRegister;
import com.javacoo.event.client.support.EventMetaData;
import com.javacoo.event.client.utils.AsmUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * ASM实现事件注册
 * <p>说明:Asm实现</p>
 * <li></li>
 *
 * @author duanyong@jccfc.com
 * @date 2021/10/16 7:50
 */
@Slf4j
@Configuration
public class AsmEventRegister extends BaseEventRegister implements ApplicationContextAware {

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        //设置applicationContext
        ApplicationContextProvider.setApplicationContext(applicationContext);
        //查找Service
        Set<EventMetaData> eventMetaDatas = getEventMetaDatas(Service.class, MySubscribe.class);

        if(EventHolder.getEventHelper().isPresent() & !eventMetaDatas.isEmpty()){
            eventMetaDatas.forEach(eventMetaData -> {
                List<String> methodNames = eventMetaData.getTargetMethods().stream().map(method -> method.getName()).collect(
                    Collectors.toList());
                Class newCalss = AsmUtil.getInstance().addAnntation(methodNames, "Lcom/google/common/eventbus/Subscribe;", eventMetaData.getTargetClass());
                if(newCalss != null){
                    log.info("事件元数据:{}",eventMetaData);
                    ApplicationContextProvider.registerBean(eventMetaData.getBeanName(),newCalss);
                    Object newObject =ApplicationContextProvider.getBean(eventMetaData.getBeanName());
                    if(newObject != null){
                        log.info("注册监听对象:{}",newObject);
                        EventHolder.getEventHelper().get().register(newObject);
                    }
                }
            });
        }
    }
}
